package com.qqbot.aspect;

import com.qqbot.annotation.GroupAnnotation;
import com.qqbot.exception.BusinessException;
import com.qqbot.service.group.GroupsService;
import com.qqbot.service.user.UserService;
import com.qqbot.utils.Constant;
import love.forte.simbot.event.GroupMessageEvent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author 付亚全
 */
@Aspect
@Component
public class GroupAspect {

    @Resource
    private UserService userService;

    @Resource
    private GroupsService groupsService;

    @Before("@annotation(com.qqbot.annotation.GroupAnnotation)")
    public void groupBefore(JoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        GroupAnnotation annotation = method.getAnnotation(GroupAnnotation.class);
        boolean master = annotation.value();
        Object[] args = joinPoint.getArgs();
        boolean result = true;
        for (Object arg : args) {
            if (arg instanceof GroupMessageEvent) {
                GroupMessageEvent event = (GroupMessageEvent) arg;
                String bot = event.getBot().getId().toString();
                String qq = event.getAuthor().getId().toString();
                String groupNo = event.getGroup().getId().toString();
                result = master ? userService.isItMaster(bot, qq, groupNo) : groupsService.isItEnable(bot, groupNo);
            }
            if (!result) {
                String methodName = joinPoint.getSignature().getDeclaringType().getSimpleName() + "." + joinPoint.getSignature().getName();
                throw new BusinessException(methodName + "账号或群组" + Constant.NO_PERMISSION);
            }
        }
    }

}
